﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using DataAccess;

namespace DataService
{
    public abstract class ServiceBase<TTable> 
        where TTable : class, IIdentifier, ICopyable<TTable>
    {
        protected string _connectionString;

        protected ServiceBase(string connectionString)
        {
            _connectionString = connectionString;
        }

        public virtual TTable CreateItem(TTable item)
        {
            using (var dataContext = new DataContext(_connectionString))
            {
                var itemNew = item;
                var table = dataContext.GetTable<TTable>();
                table.InsertOnSubmit(itemNew);
                dataContext.SubmitChanges();
                return itemNew;
            }
        }

        public virtual TTable UpdateItem(TTable item)
        {
            using (var dataContext = new DataContext( _connectionString))
            {
                var updatedItem = GetRecord(item.ID);
                updatedItem.CopyFrom(item);
                dataContext.SubmitChanges();
                return updatedItem;
            }
        }

        public virtual bool RemoveItem(int id)
        {
            using (var dataContext = new DataContext(_connectionString))
            {
                var deleteItems = dataContext
                    .GetTable<TTable>()
                    .ToList();

                var di = deleteItems
                    .Where(record => record.ID.Equals(id))
                    .FirstOrDefault();

                if(di == null)
                    return false;

                dataContext
                    .GetTable<TTable>()
                    .DeleteOnSubmit(di);
                dataContext.SubmitChanges();
                return true;
            }
        }

        public virtual List<TTable> GetAllItems()
        {
            using (var dataContext = new DataContext(_connectionString))
            {
                return dataContext
                    .GetTable<TTable>()
                    .ToList();
            }
        }

        public TTable GetRecord(int itemID)
        {
            using (var dataContext = new DataContext(_connectionString))
            {
                return GetRecord(itemID, dataContext);
            }
        }

        protected abstract TTable GetRecord(int itemID, DataContext dataContext);
    }
}
